package com.woorigil.social.parser.oclock;

import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.woorigil.social.DateUtils;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.deal.Deal;
import com.woorigil.social.domain.deal.DealListDocument;
import com.woorigil.social.domain.deal.ManageStatus;
import com.woorigil.social.parser.XmlParser;

@Component (value="oclockXmlParser")
public class OclockXmlParser extends XmlParser {
	private static Logger log = LoggerFactory.getLogger(OclockXmlParser.class);
	
	@Value("${oclock.deal.path}") 
	String dealPath;
	
	static Map<Integer, List<String>> shoppings = new HashMap<Integer, List<String>>() {{
		put(2, Arrays.asList("보정", "남성의류", "남녀공용의류", "여성의류"));
		put(3, Arrays.asList("스포츠신발", "시계", "준보석", "진보석", "가방", "지갑", "패션신발", "패션소품", "액세서리", "화장품"));
		put(4, Arrays.asList("이미용기기", "이미용품"));
		put(5, Arrays.asList("농산물", "수산물", "축산물", "가공식품", "건강식품"));
		put(6, Arrays.asList("스포츠용품", "레저", "레저용품", "스포츠의류", "헬스"));
		put(7, Arrays.asList("정보기기", "컴퓨터하드웨어", "통신기기", "디지털기기"));
		put(8, Arrays.asList("계절가전", "생활가전", "음향가전", "주방가전", "영상가전"));	//가전
		put(9, Arrays.asList("출산용품", "완구", "유아동도서", "임부용의류", "유아동잡화", "유아동의류", "발육용품"));
		put(10, Arrays.asList("수예", "자동차", "주방", "생활잡화", "욕실용품", "건강용품"));
		put(11, Arrays.asList("침구", "커튼", "수납용품", "인테리어용품", "시스템가구", "생활가구", "취미"));
		put(12, Arrays.asList("교환권", "상품권", "이용권"));
//		put(100, Arrays.asList("일반", "교육문화서비스", "수입대행", "일반도서", "의료기기"));
	}};	

	public int extractCategoryId(Deal deal) {
		if (!"쇼핑".equals(deal.getSection1())) {
			return 100;
		}
		
		for (Entry<Integer, List<String>> entry : shoppings.entrySet()) {
			for (String each : entry.getValue()) {
				if (each.equals(deal.getSection2())) {
					return entry.getKey();
				}
			}
		}
		return 100;
	}
	
	
	@Override
	public String getCharsetName() {
		return "UTF-8";
	}

	@Override
	public ProviderCode getProviderCode() {
		return ProviderCode.OC;
	}
	
	@Override
	public String getSourcePath() {
		return dealPath;
	}

	@Override
	public DealListDocument parse(Reader reader) throws ValidityException, ParsingException, IOException {
		Builder builder = new Builder();
		Document doc = builder.build(reader);
		Element root = doc.getRootElement();
		
		DealListDocument dealListDocument = new DealListDocument();
		dealListDocument.setSourceProvider("오클락");
		dealListDocument.setVersion("");
		dealListDocument.setHomepage("http://www.oclock.co.kr");
		dealListDocument.setLogo("");
		
		
		Element dealsEle = root.getFirstChildElement("coupons");
		Elements dealsEles = dealsEle.getChildElements();
		for (int i = 0; i < dealsEles.size(); i++) {
			Element dealEl = dealsEles.get(i);

			Deal deal = new Deal();
			deal.setProviderCode(getProviderCode());
			deal.setMetaId(getValue(dealEl.getFirstChildElement("meta_id")));
			deal.setTitle(getValue(dealEl.getFirstChildElement("title")));
			deal.setCategory(getValue(dealEl.getFirstChildElement("category")));
			deal.setSection1(getValue(dealEl.getFirstChildElement("section1")));
			deal.setSection2(getValue(dealEl.getFirstChildElement("section2")));
			deal.setSection3(getValue(dealEl.getFirstChildElement("section3")));
			deal.setSaleStartAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("start_at")), "yyyy-MM-dd HH:mm:ss"));
			deal.setSaleEndAt(DateUtils.toDate(getValue(dealEl.getFirstChildElement("end_at")), "yyyy-MM-dd HH:mm:ss"));
			deal.setWebLink(getValue(dealEl.getFirstChildElement("url")));
			deal.setMobileLink(getValue(dealEl.getFirstChildElement("mobile_url")));
			deal.setOriginalPrice(Integer.parseInt(getValue(dealEl.getFirstChildElement("original"))));
			deal.setDiscountRate(Integer.parseInt(getValue(dealEl.getFirstChildElement("discount"))));
			deal.setSalesPrice(Integer.parseInt(getValue(dealEl.getFirstChildElement("price"))));
			deal.setMaxCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("max_count"))));
			deal.setMinCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("min_count"))));
			deal.setNowCount(Integer.parseInt(getValue(dealEl.getFirstChildElement("now_count"))));

			deal.setUseStartAt(getValue(dealEl.getFirstChildElement("use_start_at")));
			deal.setUseEndAt(getValue(dealEl.getFirstChildElement("use_end_at")));
			deal.setSalesStatus(getValue(dealEl.getFirstChildElement("status")));
			deal.setCategoryId(extractCategoryId(deal));
			
			Element imageEl = dealEl.getFirstChildElement("images");
			deal.setImageUrl1(getValue(imageEl.getFirstChildElement("image")));
			
			Element shopsEl = dealEl.getFirstChildElement("shops");
			Elements shopsEls = shopsEl.getChildElements();
			for (int k = 0; k < shopsEls.size(); k++) {
				if (k == 0) {
					deal.setShopName(getValue(dealEl.getFirstChildElement("shop_name")));
					deal.setShopAddress(getValue(dealEl.getFirstChildElement("shop_address")));
					deal.setShopTelephone(getValue(dealEl.getFirstChildElement("shop_tel")));
					deal.setShopLatitude(getValue(dealEl.getFirstChildElement("lat")));
					deal.setShopLongitude(getValue(dealEl.getFirstChildElement("lng")));
				}
			}
			deal.setImageUrl(deal.getImageUrl1());
			deal.setAverageCount((int)(deal.getNowCount() / DateUtils.getTodayCount(deal.getSaleStartAt())));
			deal.setManageStatus(ManageStatus.S);
			dealListDocument.add(deal);
		}
		
		log.info(getProviderCode() + " deal size : " + dealListDocument.getDeals().size());
		
		return dealListDocument;
	}
}
